<?php

namespace App\Models\Admin;

use App\Models\Model;

/**
 * @method static \Illuminate\Database\Eloquent\Builder byRoleId(int $roleId)
 */
class MenuModel extends Model
{
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->setTable(config('admin-api.database.menu_table'));
    }

    protected static function booted()
    {
        static::addGlobalScope('order', function (\Illuminate\Database\Eloquent\Builder $builder) {
            $builder->orderBy(config('admin-api.database.menu_table') . '.order');
        });
    }

    public function scopeByRoleId(\Illuminate\Database\Eloquent\Builder $query, int $roleId): \Illuminate\Database\Eloquent\Builder
    {
        $roleRelMenuTable = config('admin-api.database.role_menu_table');
        return $query->leftJoin($roleRelMenuTable, $roleRelMenuTable . '.menu_id', '=', $this->table . '.id')
            ->where($roleRelMenuTable . '.role_id', $roleId)
            ->select([$this->table . '.*']);
    }
}
